package com.example.gomi.intelligentcitypipe;

import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.example.gomi.intelligentcitypipe.DAO.PipeInfo;
import com.example.gomi.intelligentcitypipe.DAO.PipeInfoHelper;
import com.example.gomi.intelligentcitypipe.handler.MessageReceiveHandler;
import com.example.gomi.intelligentcitypipe.serial.SerialController;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class PipeMapActivity extends AppCompatActivity implements LocationSource,
        AMapLocationListener, AMap.OnMapLoadedListener, AMap.OnInfoWindowClickListener, AMap.OnMarkerClickListener {

    MapView mapView;

    private AMap aMap;

    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private AMapLocation mCurrentLocation = null;

    List<PipeInfo> mAllPipes = null;

    //private PipeProtocol mPipeProtocol = null;

    private boolean mHadDrawLine = false;

    private Button mGetNewPipeInfo;
    private Button mDrawPipeLine;


    private SoundPool mSoundPool;

    private MessageReceiveHandler receiveHandler;

     int[] colors = {Color.argb(255, 255, 1, 1),Color.argb(255, 1, 255, 1),Color.argb(255, 1, 1, 255)};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pipe_map);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        mGetNewPipeInfo = (Button) findViewById(R.id.getNewPipeInfo);
        mDrawPipeLine = (Button) findViewById(R.id.drawPipeLine);
        //mBtnBluetooth = (Button) findViewById(R.id.btn_bluetooth);

        mapView = (MapView) findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);
        init();
        addTestPipeInfo();
    }

    private void init() {

        mSoundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);

//        mSoundPool.load(this, R.raw.found, 1);
        mSoundPool.load(this, R.raw.found, 1);
        receiveHandler = new MessageReceiveHandler(this,  this.mSoundPool);

        PipeInfoHelper.setmContext(this);

        if (aMap == null) {
            aMap = mapView.getMap();
            setUpMap();
        }


        try {
            updateMap();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        mGetNewPipeInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getNewPipeInfoOnClick(view);
            }
        });

        mDrawPipeLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawLineOnClick(view);
            }
        });

    }

    private void getNewPipeInfoOnClick(View view) {
        if (mlocationClient !=  null) {
            AMapLocation currentLocation = mlocationClient.getLastKnownLocation();
            if (currentLocation != null) {
                Log.d("map", Double.toString(currentLocation.getLatitude()));
                Log.d("map", Double.toString(currentLocation.getLongitude()));
                mCurrentLocation = currentLocation;

//                mPipeProtocol.getNewPipeInfo();
                if (SerialController.getInstance().getmRunFlag()) {
                    SerialController.getInstance().stop();
                    mGetNewPipeInfo.setText("开始读取");
                } else {
                    SerialController.getInstance().setMessageReceiveHandler(PipeMapActivity.this.receiveHandler);
                    if (SerialController.getInstance().start()) {
                        mGetNewPipeInfo.setText("停止读取");
                    } else {
                        Toast.makeText(this, "开始读取失败，请重试", Toast.LENGTH_SHORT).show();
                        mGetNewPipeInfo.setText("开始读取");
                    }
                }

            } else {
                //TODO
            }
        } else {
            //TODO
        }
    }

    public void updateMap() throws SQLException {
        updateMap(null, false);
    }

    public void updateMap(PipeInfo pipeInfo) throws SQLException {
        updateMap(pipeInfo, false);
    }

private Set<Long> ids = new HashSet<>();
    public void addNewPipInfo(PipeInfo pipeInfo) throws SQLException{
        if(mAllPipes == null){
            mAllPipes = PipeInfoHelper.getInstance().queryAll();
        }
        if(ids.contains(pipeInfo.getPipeid())){
            return ;
        }else {
            ids.add(pipeInfo.getPipeid());
            mAllPipes.add(pipeInfo);
        }
    }

    private void updateMap(PipeInfo pipeInfo, boolean hasDrawLine) throws SQLException {
        aMap.clear(true);
        if(mAllPipes == null){
            mAllPipes = PipeInfoHelper.getInstance().queryAll();
        }

        Map<String,List<PipeInfo>> groups = new HashMap<>();
        boolean b = false;
        for(PipeInfo pp : mAllPipes)
        {
            if(pipeInfo !=null && pp.getPipeid() == pipeInfo.getPipeid()){
                Log.e("DRAW_MAP","zhao dao 000000000000000000000000000000000000000000000000000]"+pp.getPipeid());
                b = true;
            }
            String groupId  = pp.getGroupId();
            List<PipeInfo> list = groups.get(groupId);
            if(list ==null){
                list = new ArrayList<PipeInfo>();
                list.add(pp);
                groups.put(groupId,list);
            }else {
                list.add(pp);
            }

        }
        if(b){

        }else{
            Log.e("DRAW_MAP","dao 未找到。。。。。。。。。。。。。。]");
        }

        Set<Map.Entry<String, List<PipeInfo>>> entries = groups.entrySet();
        Iterator<Map.Entry<String, List<PipeInfo>>> itr = entries.iterator();
        int c = 0;
        while (itr.hasNext()) {
            Map.Entry<String, List<PipeInfo>> entry = itr.next();
            List<PipeInfo> value = entry.getValue();
            Log.e("DRAW_MAP","FFFFFFFFFFF]"+mAllPipes.size());
            c = c%colors.length;
            drawMarkerAndLine(pipeInfo,value,hasDrawLine,colors[c]);
            c++;
        }



    }

    private void drawMarkerAndLine(PipeInfo pipeInfo,List<PipeInfo> pipes, boolean hasDrawLine,int color){

        mHadDrawLine = hasDrawLine;

        for (int i = 0; i < pipes.size(); i++) {
            PipeInfo pp = pipes.get(i);
            Log.e("DRAW_MAP","FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF]------------------->" + pp.getPipeid());
            int r ;

            if(pipeInfo!=null){
                Log.e("DRAW_MAP","---->" +(pp.getPipeid() == pipeInfo.getPipeid())+"-->"+pipeInfo.getPipeid());
            }
            if (pipeInfo != null && pp.getPipeid() == pipeInfo.getPipeid()) {
                r = R.drawable.marker_current1;
                Log.e("DRAW_MAP","-----pipeInfo---->>>["+pipeInfo.getLatitude()+"," +pipeInfo.getLongitude()+"]");
            } else {
                r = R.drawable.marker_history1;
                Log.e("DRAW_MAP","-----pp---->>>["+pp.getLatitude()+"," +pp.getLongitude()+"] ===="+pp.getGroupId());

            }

            aMap.addMarker(new MarkerOptions()
                    .position(new LatLng(pp.getLatitude(), pp.getLongitude()))
                    .title(pp.toString())
                    .icon(BitmapDescriptorFactory.fromResource(r))
                    .draggable(false));


            if (hasDrawLine && i > 0) {
                PipeInfo prePipeInfo = pipes.get(i - 1);
                aMap.addPolyline((new PolylineOptions())
                        .add(new LatLng(pp.getLatitude(), pp.getLongitude()),
                                new LatLng(prePipeInfo.getLatitude(), prePipeInfo.getLongitude()))
                        .width(10).setDottedLine(true).geodesic(true)
                        .color(color));
            }
        }

    }


    private void drawLineOnClick(View view) {
        try {
            if (!mHadDrawLine) {
                updateMap(this.receiveHandler.getPipeInfo(), true);
                mHadDrawLine = true;
            } else {
                updateMap();
                mHadDrawLine = false;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.location_marker));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);

        aMap.setOnMapLoadedListener(this);
        aMap.setOnInfoWindowClickListener(this);

        aMap.setOnMarkerClickListener(this);

        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }


    @Override
    public void onInfoWindowClick(Marker marker) {
        marker.hideInfoWindow();

        String tmp = marker.getTitle();
        String[] s = tmp.split("\n");
        Intent intent = new Intent();
        int id  = Integer.valueOf(s[0].substring(3));
        Log.e("参数。。。。。。。。。。。。。。。。。。。。。","------------------->"+id);
        intent.putExtra("id",id);
        intent.setClass(this, PipeDetailActivity.class);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            try {
                updateMap();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onMapLoaded() {
        // 设置所有maker显示在当前可视区域地图中

        LatLngBounds bounds;
        try {
            List<PipeInfo> tmpList = PipeInfoHelper.getInstance().queryAll();
            if (tmpList.size() > 2) {
                LatLng latLng1 = new LatLng(tmpList.get(0).getLatitude(), tmpList.get(0).getLongitude());
                LatLng latLng2 = new LatLng(tmpList.get(1).getLatitude(), tmpList.get(1).getLongitude());
                bounds = new LatLngBounds.Builder().include(latLng1).include(latLng2).build();
                for (PipeInfo info : tmpList) {
                    LatLng tmp = new LatLng(info.getLatitude(), info.getLongitude());
                    bounds = bounds.including(tmp);
                }
                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        PipeInfoHelper.closeHelper();
        //SerialController.getInstance().stop();
        //mPipeProtocol.stopGetPipeInfo();
        mGetNewPipeInfo.setText("开始读取");
//        SerialController.getInstance().DestroyAccessory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        deactivate();
        mapView.onDestroy();
        //mPipeProtocol.stopGetPipeInfo();
        PipeInfoHelper.closeHelper();
        //SerialController.getInstance().stop();
        SerialController.getInstance().DestroyAccessory();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        PipeInfoHelper.setmContext(this);
        //測試時，开启蓝牙直接读取
        //SerialController.getInstance().setMessageReceiveHandler(receiveHandler);
        //SerialController.getInstance().start();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }



    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        Log.d("map", "你点击的是" + marker.getTitle()+" -->"+marker.getId());

        return false;
    }


    public AMapLocation getAMapLocation(){
        if(this.mCurrentLocation==null){
            if (mlocationClient != null) {
                this.mCurrentLocation = mlocationClient.getLastKnownLocation();
            }

        }
        return this.mCurrentLocation;
    }


    /**
     * 添加測試点
     */
    private void addTestPipeInfo() {
        Log.e("initmap","map ok??");
        double[][] lls = new double[4][2];
        lls = new double[][]{{120.326262,31.484433},
                {120.326401,31.484098},
                {120.326491,31.482859},
                {120.327016,31.483859}};

        double[][] lls1 = new double[5][2];
        lls1 = new double[][]{{120.329024,31.485029},
                {120.329285,31.484483},
                {120.329518,31.483919},
                {120.329716,31.483467},
                {120.329972,31.482866}};


        for (int i =0;i<lls.length;i++){
            double latitude =lls[i][1];
            double longitude =lls[i][0];

            PipeInfo pipeInfo = new PipeInfo();
            pipeInfo.setLatitude(latitude);
            pipeInfo.setLongitude(longitude);
            pipeInfo.setHumidity(20);
            pipeInfo.setTemperature(18);
            pipeInfo.setPipeid((long)(latitude*100000));
            pipeInfo.setGroupId("lls");
            try{
                PipeInfoHelper.getInstance().addPipe(pipeInfo);
            }catch (Exception e){
e.printStackTrace();
            }
        }

        for (int i =0;i<lls1.length;i++){
            double latitude =lls1[i][1];
            double longitude =lls1[i][0];

            PipeInfo pipeInfo = new PipeInfo();
            pipeInfo.setLatitude(latitude);
            pipeInfo.setLongitude(longitude);
            pipeInfo.setHumidity(20);
            pipeInfo.setTemperature(18);
            pipeInfo.setPipeid((long)(latitude*100000));
            pipeInfo.setGroupId("lls1");
            try{
                PipeInfoHelper.getInstance().addPipe(pipeInfo);
            }catch (Exception e){
e.printStackTrace();
            }
        }



    }

}
